import Toast from "tdesign-miniprogram/toast";
import { bindPhone } from "../../api/auth";
import { delay } from "../../utils/index";

Component({
  properties: {
    visible: {
      type: Boolean,
      value: false,
    },
    openid: {
      type: String,
      value: "",
    },
  },

  data: {
    phone: "",
    code: "",
    phoneError: false,
    description: "为了提供更好的服务，我们需要您的手机号进行身份验证", // 手机号必要性说明
    useWechatPhone: true, // 优先展示微信获取手机号
  },

  methods: {
    onPhoneCodeInputChange(e) {
      const { phone, phoneError, code } = e.detail;
      this.setData({
        phone,
        phoneError,
        code,
      });
    },

    async onGetPhoneNumber(e) {
      if (e.detail.errMsg === "getPhoneNumber:ok") {
        // 用户同意授权，获取到加密数据
        const { encryptedData, iv } = e.detail;
        // 在这里调用后端接口解密手机号并进行绑定
        console.log("微信手机号授权成功", encryptedData, iv);
        this.showToast({
          title: "手机号获取成功",
          icon: "success",
        });
        this.triggerEvent("confirm", {
          wechatPhoneData: { encryptedData, iv },
        });
      } else {
        // 用户拒绝授权
        this.showToast({
          title: "您已拒绝微信授权,自动切换为手动输入",
          icon: "none",
        });
        await delay(1200);
        this.setData({
          useWechatPhone: false, // 切换到手动输入
        });
      }
    },

    togglePhoneInputMethod() {
      this.setData({
        useWechatPhone: !this.data.useWechatPhone,
      });
    },

    onClose() {
      this.setData({ visible: false });
      this.triggerEvent("close");
    },

    showToast(options = {}) {
      Toast({
        context: this,
        selector: "#t-toast",
        message: options.title,
      });
    },

    async onBindPhone() {
      if (!this.data.phone) {
        this.showToast({ title: "请输入手机号", icon: "none" });
        return;
      }
      if (this.data.phoneError) {
        this.showToast({ title: "请输入验证码", icon: "none" });
        return;
      }
      if (this.data.phoneError) {
        this.showToast({ title: "手机号格式不正确", icon: "none" });
        return;
      }

      try {
        // const data = {
        //   action: "bind_phone",
        //   sms_code: this.data.code,
        //   phone: this.data.phone, // Use the phone from component data
        //   wechat_openid: this.properties.openid,
        // };
        // console.log("边缘函数请求参数:", data);
        const res = await bindPhone({
          phone: this.data.phone,
          code: this.data.code,
          openid: this.properties.openid,
        });
        if (res.error) {
          this.showToast({
            title: res.error.message || "绑定失败",
            icon: "error",
          });
          return;
        }
        console.log("边缘函数响应:", res.data);
        this.onClose();
        this.triggerEvent("bindsuccess", res.data);
      } catch (error) {
        console.error("绑定失败", error);
        // 错误提示已在 request.js 中统一处理
      }
    },
  },
});
